const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const io = require('socket.io')(server, {
  cors: {
    origin: ['http://localhost:5173', 'http://localhost:5174', 'https://ylcweb.cn', 'http://ylcweb.cn'],
    methods: ["GET", "POST"],
    credentials: true
  }
});

// 跟踪在线用户和共享状态
const users = new Set();
const sharingUsers = new Map(); // 记录正在共享的用户
const rooms = new Map(); // 存储房间信息 { roomId: { host: socketId, viewers: Set<socketId> } }

io.on('connection', (socket) => {
  console.log('用户连接:', socket.id);
  users.add(socket.id);

  // 创建房间
  socket.on('create-room', (callback) => {
    const roomId = Math.random().toString(36).substring(2, 8); // 生成6位随机房间号
    rooms.set(roomId, {
      host: socket.id,
      viewers: new Set()
    });
    socket.join(roomId);
    callback(roomId);
  });

  // 加入房间
  socket.on('join-room', ({ roomId }, callback) => {
    const room = rooms.get(roomId);
    if (!room) {
      callback({ success: false, message: '房间不存在' });
      return;
    }

    // 如果用户已经在房间中，先将其移除
    if (room.viewers.has(socket.id)) {
      room.viewers.delete(socket.id);
    }

    socket.join(roomId);
    room.viewers.add(socket.id);
    
    // 通知房主有新观众加入
    io.to(room.host).emit('new-viewer', {
      userId: socket.id,
      roomId,
      isNewJoin: true
    });
    
    // 通知房间内的其他观众有新成员加入
    room.viewers.forEach(viewerId => {
      if (viewerId !== socket.id) {
        io.to(viewerId).emit('viewer-joined', {
          userId: socket.id,
          roomId
        });
      }
    });
    
    callback({ 
      success: true, 
      hostId: room.host,
      viewers: Array.from(room.viewers)
    });
  });

  // 处理重连请求
  socket.on('reconnect-request', ({ userId, targetUserId }) => {
    console.log(`用户 ${userId} 请求与 ${targetUserId} 重新建立连接`);
    
    // 如果目标用户确实在共享中
    if (sharingUsers.has(targetUserId)) {
      // 清理旧的共享状态（如果存在）
      sharingUsers.delete(userId);
      
      // 通知共享者重新发送 offer
      io.to(targetUserId).emit('new-viewer', userId);
      
      // 可选：通知请求重连的用户
      socket.emit('reconnect-initiated');
    }
  });

  // 获取在线用户列表
  socket.on('get-users', (callback) => {
    callback(Array.from(users));
  });

  // 处理offer
  socket.on('offer', ({ offer, userId, targetUserId, roomId }) => {
    console.log(`转发 offer 从 ${userId} 到 ${targetUserId} 在房间 ${roomId}`);
    sharingUsers.set(userId, offer); // 记录共享状态
    socket.to(targetUserId).emit('offer', { offer, userId, targetUserId, roomId });
  });

  // 处理answer
  socket.on('answer', ({ answer, userId, targetUserId }) => {
    console.log(`转发 answer 从 ${userId} 到 ${targetUserId}`);
    socket.to(targetUserId).emit('answer', { answer, userId });
  });

  // 处理ICE候选
  socket.on('ice-candidate', ({ candidate, userId, targetUserId }) => {
    console.log(`转发 ICE candidate 从 ${userId} 到 ${targetUserId}`);
    socket.to(targetUserId).emit('ice-candidate', { candidate, userId });
  });

  // 处理共享结束
  socket.on('share-ended', (roomId) => {
    const room = rooms.get(roomId);
    console.log(`共享结束 ${roomId}, ${socket.id}, ${room}`);
    
    if (room) {
      io.to(roomId).emit('share-ended', socket.id);
      rooms.delete(roomId); // 删除房间
    }
  });

  socket.on('leave-room', (roomId) => {
    console.log(`用户 ${socket.id} 离开房间 ${roomId}`);
    const room = rooms.get(roomId);
    if (room) {
      if (room.host === socket.id) {
        // 如果是房主离开，通知所有观众并删除房间
        io.to(roomId).emit('host-left', roomId);
        rooms.delete(roomId);
      } else if (room.viewers.has(socket.id)) {
        // 如果是观众离开，从观众列表中移除并通知房主
        room.viewers.delete(socket.id);
        io.to(room.host).emit('viewer-left', {
          userId: socket.id,
          roomId
        });
      }
      socket.leave(roomId);
    }
  });

  // 修改断开连接处理
  socket.on('disconnect', () => {
    users.delete(socket.id);
    
    rooms.forEach((room, roomId) => {
      if (room.host === socket.id) {
        // 如果是房主断开，通知所有观众并删除房间
        io.to(roomId).emit('host-left', roomId);
        rooms.delete(roomId);
      } else if (room.viewers.has(socket.id)) {
        // 如果是观众断开，从观众列表中移除并通知房主
        room.viewers.delete(socket.id);
        io.to(room.host).emit('viewer-left', {
          userId: socket.id,
          roomId
        });
      }
    });
  });
});

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`信令服务器运行在端口 ${PORT}`);
});
